import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_base_kit/home/video/controller/video_list_controller.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../../../utils/log_util.dart';

///代码清单12-12
class VideoDetailController extends GetxController {
  //创建视频播放控制器
  VideoPlayerController? playController;
  //当前控制器对应的tag
  final String? tag;
  //当前播放状态
  bool isPlay = false;

  VideoDetailController({this.tag});

  ///代码清单12-12-1 暂停播放
  void pause([bool destroy=false]) {
    //视频暂停
    playController!.pause();
    isPlay = false;
    //非销毁时 需要更新页面显示
    if(!destroy) {
      update([tag ?? '']);
    }
  }

  //播放视频
  void play() async {
    //点击同一个视频
    if (playController != null) {
      if (playController!.value.isPlaying) {
        playController!.play();
      }
    }
    //校验是否有其他视频在播放
    VideoListController listController = Get.find<VideoListController>();
    await listController.stopGlobalVideo();

    //创建新的视频播放控制器
    playController = VideoPlayerController.asset('assets/video/list_item.mp4');
    //更新列表中的记录
    listController.updateVideoController(playController, tag);
    //添加监听
    playController!.addListener(() {
      if (isPlay && !playController!.value.isPlaying) {
        //视频播放的当前时间进度
        Duration currentDuration = playController!.value.position;
        //视频的总时长
        Duration totalDuration = playController!.value.duration;
        if (currentDuration == totalDuration) {
          isPlay = false;
          update([tag??'']);
        }
      }
    });
    //初始化
    await playController!.initialize();
    //当前视频 播放的位置
    Duration postion = playController!.value.position;
    //视频的总长度
    Duration duration = playController!.value.duration;

    if (postion == duration) {
      //播放完毕 再点击播放时，当播放位置滑动到开始位置
      playController!.seekTo(Duration.zero);
    }
    //开始播放
    playController!.play();
    isPlay = true;
    update([tag??'']);
  }

  @override
  void onClose() {
    if (playController != null) {
      playController!.pause();
      playController!.dispose();
    }
    super.onClose();
  }

}
